package com.duqc.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName RedisSentinelConfig
 * @Description redis 主从哨兵版
 * @Author duqc
 * @Date 2021/4/29
 **/
@Slf4j
//@Configuration
//@EnableAutoConfiguration
public class RedisSentinelConfig {

    @Value("#{'${spring.redis.sentinel.nodes}'.split(',')}")
    private List<String> nodes;

    @Value("${spring.redis.sentinel.master}")
    private String master;

    @Value("${spring.redis.password}")
    private String password;

//    @Bean
//    @ConfigurationProperties(prefix = "spring.redis")
    public JedisPoolConfig getRedisConfig() {
        return new JedisPoolConfig();
    }

//    @Bean
    public RedisSentinelConfiguration sentinelConfiguration() {
        RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
        //配置matser的名称
        redisSentinelConfiguration.master(master);
        redisSentinelConfiguration.setPassword(password);
        //配置redis的哨兵sentinel
        Set<RedisNode> redisNodes = new HashSet<>();
        nodes.forEach(info -> {
            redisNodes.add(new RedisNode(info.split(":")[0], Integer.parseInt(info.split(":")[1])));
        });
        log.info("redisNodes -->" + redisNodes);
        redisSentinelConfiguration.setSentinels(redisNodes);
        return redisSentinelConfiguration;
    }

//    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig,
                                                         RedisSentinelConfiguration sentinelConfiguration) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfiguration, jedisPoolConfig);
        log.info(jedisConnectionFactory.getPassword());
        return jedisConnectionFactory;
    }
}
